
package com.ttomato.game.framework.gl;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.khronos.opengles.GL10;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLUtils;

import com.ttomato.game.framework.FileIO;
import com.ttomato.game.framework.impl.GLGame;
import com.ttomato.game.framework.impl.GLGraphics;

public class Texture {
    GLGraphics mGlGraphics;
    FileIO mFileIO;
    String mFileName;
    int mTextureId;
    int mMinFilter;
    int mMagFilter;

    public Texture(GLGame glGame, String fileName) {
        this.mGlGraphics = glGame.getGLGraphics();
        this.mFileIO = glGame.getFileIO();
        this.mFileName = fileName;
        load();
    }

    private void load() {
        GL10 gl = mGlGraphics.getGl();
        int[] textureIds = new int[1];
        gl.glGenTextures(1, textureIds, 0);
        mTextureId = textureIds[0];

        InputStream in = null;
        try {
            in = mFileIO.readAsset(mFileName);
            Bitmap bitmap = BitmapFactory.decodeStream(in);
            gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureId);
            GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
            setFilters(GL10.GL_NEAREST, GL10.GL_NEAREST);
            gl.glBindTexture(GL10.GL_TEXTURE_2D, 0);
        } catch (Exception e) {
            throw new RuntimeException("Couldn't load texture '" + mFileName + "'", e);
        } finally {
            if (in != null)
                try {
                    in.close();
                } catch (IOException e) {
                }
        }
    }

    public void reload() {
        load();
        bind();
        setFilters(mMinFilter, mMagFilter);
        mGlGraphics.getGl().glBindTexture(GL10.GL_TEXTURE_2D, 0);
    }

    public void setFilters(int minFilter, int magFilter) {
        this.mMinFilter = minFilter;
        this.mMagFilter = magFilter;
        GL10 gl = mGlGraphics.getGl();
        gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, minFilter);
        gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, magFilter);
    }

    public void bind() {
        GL10 gl = mGlGraphics.getGl();
        gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureId);
    }

    public void dispose() {
        GL10 gl = mGlGraphics.getGl();
        gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureId);
        int[] textureIds = {
                mTextureId
        };
        gl.glDeleteTextures(1, textureIds, 0);
    }
}
